package com.varian.security.handler;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.varian.log.util.LogUtil;
import com.varian.security.util.SecurityUtil;
import com.varian.tool.Func;
import com.varian.tool.contant.ResultConstant;
import com.varian.tool.result.IR;
import com.varian.tool.result.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author ben
 * @since 2024/6/24
 */
@Slf4j
public class VarianAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String message;
        if (authException instanceof InvalidBearerTokenException tokenException) {
            log.warn("无效的token: {}", tokenException.getMessage());
            message = "登录已失效，请重新登录";
        } else {
            log.warn("未认证: {}", authException.getMessage());
            message = authException.getMessage();
        }
        IR result = R.result(ResultConstant.UNAUTHORIZED, ResultConstant.FAIL_CODE, message);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setStatus(result.getStatus());
        LogUtil.apiErrorLog(Func.getServletRequest(), authException, result, SecurityUtil.getUserIdOnSafe());
        JakartaServletUtil.write(response, Func.jackson2JsonStr(result), MediaType.APPLICATION_JSON_VALUE);
    }
}
